import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

import { UserService } from '@src/user/user.service';
import { User } from '@src/user/entity/user.entity';

import { JwtPayload } from './type/jwt-payload.type';
import { AuthLoginRespDto } from './dto/auth-login.resp.dto';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UserService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, pass: string): Promise<User | null> {
    const user = await this.usersService.findOneByUsername(username);
    if (user && user.password === pass) {
      return user;
    }
    return null;
  }

  async login(user: User): Promise<AuthLoginRespDto> {
    const payload: JwtPayload = { username: user.username, sub: user.id };
    return {
      token: this.jwtService.sign(payload),
    };
  }
}
